(function(){
	var AjaxCrud = QualityCheck.AjaxCRUD;
	var serverUrl = QualityCheck.GPUD.ServiceConfig;
	var currentPage = 1;
	var pageSize = 10;
	var totalSize;
	var now = 0;
	var setting = {
		check: {
			enable: true
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		view: {
			showIcon: false,
			showLine: false,
			
		}
	};
	$(function(){
		var usercode = $("#user-name",parent.parent.document).attr("code");
		var userkey = $("#user-name",parent.parent.document).attr("key");
		var usertype = $("#user-name",parent.parent.document).attr("usertype");
		keyCheck(usercode,usertype,userkey,function(){
			initSmPages();
			window.onresize = function () {
				initSmPages();
			};
			pagebtns();
			initRole(currentPage,pageSize);
		});
	});
	function initRole(currentpage,pagesize){
		var userKey = $("#user-name",parent.parent.document).attr("key");	
		var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
		var name = encodeURI($("#role-name").val());
		var data = {
				cmd:"getRole",
				model:"license",
				userKey:userKey,
				data:{
					currentpage:currentpage,
					pagesize:pagesize,
					schoolcode:schoolcode,
					name:name,
				},
				remark:"",
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			var content = "";
			var pagecontent = "<div class=\"pages-btn-next\">&gt;&gt;</div>";
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var data = res.data.data;
				var total = res.data.total;
				totalSize = Math.ceil(total/pagesize);
				if(totalSize <= 5 && totalSize >0){
					for(var i = totalSize-1 ; i >= 0; i--){
						if(i == currentpage-1){
							pagecontent += "<div class=\"pages-btn page-btn-select\">"+(i + 1)+"</div>"; 
						}else{
							pagecontent += "<div class=\"pages-btn\">"+(i + 1)+"</div>"; 
						}
					}
				}else if(totalSize == 0){
					pagecontent += "<div class=\"pages-btn\">1</div>";
				}else if(totalSize > 5){
					var lastp = (now*5)+5;
					if(lastp > totalSize){
						lastp = totalSize;
					}
					for(var i = lastp-1 ; i >= (now*5); i--){
						if(i == currentpage-1){
							pagecontent += "<div class=\"pages-btn page-btn-select\">"+(i + 1)+"</div>"; 
						}else{
							pagecontent += "<div class=\"pages-btn\">"+(i + 1)+"</div>"; 
						}
					}
				}
				pagecontent += "<div class=\"pages-btn-last\">&lt;&lt;</div>";
				$("#role-page").empty();
				$("#role-page").append(pagecontent);
				
				$(".pages-btn").unbind("click");
				$(".pages-btn").click(function(){
					dataCache = [];
					$(".pages-btn").removeClass("page-btn-select");
					$(this).addClass("page-btn-select");
					currentPage = parseInt($(this).text());
					initRole(currentPage,pageSize);
				});
				
				$(".pages-btn-last").unbind("click");
				$(".pages-btn-last").click(function(){
					if(totalSize <= 5 && totalSize >0){
						return false;
					}else if(totalSize == 0){
						return false;
					}else if(totalSize > 5){
						if(now > 0){
							now --;
							initRole((now*5+1),pageSize);
						}else{
							return false;
						}
					}
				});
				
				$(".pages-btn-next").unbind("click");
				$(".pages-btn-next").click(function(){
					if(totalSize <= 5 && totalSize >0){
						return false;
					}else if(totalSize == 0){
						return false;
					}else if(totalSize > 5){
						if(totalSize%5 == 0){
							if((now+1) < totalSize/5){
								now ++;
								initRole((now*5+1),pageSize);
							}else{
								return false;
							}
						}else{
							if((now+1) <= (totalSize-totalSize%5)/5){
								now ++;
								initRole((now*5+1),pageSize);
							}else{
								return false;
							}
						}
					}
				});
				if(data.length > 0){
					for(var i = 0; i < data.length; i++){
						for(var key in data[i]){
							if(data[i][key] == null || data[i][key] == "null" ){
								data[i][key] = "";
							}
						}
						content += "<div class=\"table-trs\">" +
							"<div class=\"tables-headimg\">" +
//								"<img src=\"../../../../../../"+ServiceName+data[i].headimg+"\" width=\"100%\" height=\"100%\"/>" +
							"</div>" +
							"<div class=\"tables-left\">" +
								"<div class=\"table-name\" title=\""+data[i].name+"\" style='width:400px;text-align:left;'\>"+substr(data[i].name,8)+"</div>" +
								"<div class=\"table-code\" title='"+data[i].describe+"'style='width:400px;text-align:left;'>"+substr(data[i].describe,25)+"</div>" +
							"</div>" +
//							"<div class=\"tables-middle\">" +
//								"<div class=\"table-class\" title=\"手机号\">"+isUndefined(data[i].cellphone)+"</div>" +
//								"<div class=\"table-code\">"+isUndefined(data[i].email)+"</div>" +
//							"</div>" +
							"<div class=\"tables-right\">" +
								"<div class=\"table-address\">所属学校： "+data[i].schoolname +"</div>" +
								"<div class=\"table-oprate\">" +
									"<div class=\"table-modelpower\" dataindex = \""+i+"\" code=\""+data[i].code+"\" title=\"功能授权\"></div>" +
									"<div class=\"table-datapower\" dataindex = \""+i+"\" code=\""+data[i].code+"\" title=\"数据授权\"></div>" +
								"</div>" +
							"</div>" +
						"</div>";
					}
					$("#role-data-show").empty();
					$("#role-data-show").append(content);
					
					$(".table-trs").unbind("hover");
					$(".table-trs").hover(function(){
						$(this).find(".table-oprate").show();
					},function(){
						$(".table-oprate").hide();
					});
					//功能授权
					$(".table-modelpower").unbind("click");
					$(".table-modelpower").click(function(){
						var rolecode = $(this).attr("code");
						showModelDialog(rolecode);
					});
					//数据授权
					$(".table-datapower").unbind("click");
					$(".table-datapower").click(function(){
						var rolecode = $(this).attr("code");
						showDataDialog(rolecode);
					});				
				}else{
					content += "<div class=\"table-trs\">" +
									"<div class=\"no-data-show\">没有查到相关结果！</div>" +
								"</div>";
					$("#role-data-show").empty();
					$("#role-data-show").append(content);
				}
			}else{
				content += "<div class=\"table-trs\">" +
								"<div class=\"no-data-show\">没有查到相关结果！</div>" +
							"</div>";
				$("#role-data-show").empty();
				$("#role-data-show").append(content);
			}
		},null,null);	
	}
	function showModelDialog(rolecode){
		var contents = "<div class='index-dialog-content-data'><ul class='ztree' id='modelpower-tree'></ul></div>";
		var obj = {
				width:400,
				height:420,
				title:"功能授权",
				contents:contents
			  };
		userChoice(obj,function(){
			initModelNodes(rolecode);
			$("#sure-btn",parent.parent.document).unbind("click");
			$("#sure-btn",parent.parent.document).bind("click",function(){
				modelPower(rolecode);
				$(".index-dialog",parent.parent.document).hide();
				$(".index-dialog-cover",parent.parent.document).hide();
			});
			$("#cancel-btn",parent.parent.document).unbind("click");
			$("#cancel-btn",parent.parent.document).bind("click",function(){
				$(".index-dialog",parent.parent.document).hide();
				$(".index-dialog-cover",parent.parent.document).hide();
			});
		});
	}
	function modelPower(rolecode){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var treeObj = $.fn.zTree.getZTreeObj("modelpower-tree");
		var nodes = treeObj.getCheckedNodes(true);
		var paramsArr = [];
		if(nodes.length > 0){
			for(var i = 0; i < nodes.length; i++){
				if(nodes[i].level > 0){
					var params = {};
					params["rolecode"] = rolecode;
					params["modular"] = nodes[i].id;
					paramsArr.push(params);
				}
			}
		}else{
			var param = {};
			param["rolecode"] = rolecode;
			paramsArr.push(param);
		}
		var data = {
				cmd:"addLicenseRoleModels",
				model:"license",
				userKey:userKey,
				data:JSON.stringify(paramsArr),
				remark:"",						
		};
		processBegin("正在运行中···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1 && res.data != undefined && res.data != ""){
				processEnd("功能授权成功");
			}else{
				processError("功能授权失败");
			}
		},null,null);
	}
	
	function initModelNodes(rolecode){
		$(".loading",parent.parent.document).show();
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var data = {
				cmd:"queryModels",
				model:"license",
				userKey:userKey,
				data:{},
				remark:"",						
		};
		AjaxCrud.get2(serverUrl.ServerLoginUrl,data,function(res){
			var modelNodes = [];
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var root1 = {
						id: "selectAllModels",
						pId: -1,
						name : "全部",
						open: true,
						icon: "",
				};
				modelNodes.push(root1);
				var data = res.data; 
				for(var i = 0; i < data.length; i++){
					var root2 = {
							id: data[i].code,
							pId: "selectAllModels",
							name : data[i].value,
							open: true,
							icon: getIconUrl(data[i].icon),
					};
					modelNodes.push(root2);
					var children = data[i].children;
					for(var j = 0; j < children.length; j++){
						var root3 = {
								id: children[j].code,
								pId: data[i].code,
								name: children[j].value,
								open: true,
								icon: getIconUrl(children[j].icon),
						};
						modelNodes.push(root3);
						var children1 = children[j].children;
						if(children1 != undefined){
							for(var k = 0; k < children1.length; k++){
								var root4 = {
										id: children1[k].code,
										pId: children[j].code,
										name: children1[k].value,
										open: true,
										icon: getIconUrl(children1[k].icon),
								};
								modelNodes.push(root4);
							}
						}
					}
				}
				$.fn.zTree.init($("#modelpower-tree",parent.parent.document), setting, modelNodes);
				getselectedModels(rolecode);
			}else{
				$(".loading",parent.parent.document).hide();
			}
		},null,null);
	}
	
	function showDataDialog(rolecode){
		var contents = "<div class='index-dialog-content-data'><ul class='ztree' id='datapower-tree'></ul></div>";
		var obj = {
				width:400,
				height:420,
				title:"数据授权",
				contents:contents
			  };
		userChoice(obj,function(){
			initDataNodes(rolecode);
			$("#sure-btn",parent.parent.document).unbind("click");
			$("#sure-btn",parent.parent.document).bind("click",function(){
				dataPower(rolecode);
				$(".index-dialog",parent.parent.document).hide();
				$(".index-dialog-cover",parent.parent.document).hide();
			});
			$("#cancel-btn",parent.parent.document).unbind("click");
			$("#cancel-btn",parent.parent.document).bind("click",function(){
				$(".index-dialog",parent.parent.document).hide();
				$(".index-dialog-cover",parent.parent.document).hide();
			});
		});
	}
	function dataPower(rolecode){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var treeObj = $.fn.zTree.getZTreeObj("datapower-tree");
		var nodes = treeObj.getCheckedNodes(true);
		var paramsArr = [];
		if(nodes.length > 0){
			for(var i = 0; i < nodes.length; i++){
				if(nodes[i].level == 3){
					var params = {};
					params["rolecode"] = rolecode;
					params["grade"] = nodes[i].grade; 
					params["classcode"] = nodes[i].id;
					params["classes"] = nodes[i].classes;
					params["type"] = nodes[i].type;
					paramsArr.push(params);
				}
			}
		}else{
			var param = {};
			param["rolecode"] = rolecode;
			paramsArr.push(param);
		}
		var data = {
				cmd:"batchAddDataRole",
				model:"license",
				userKey:userKey,
				data:JSON.stringify(paramsArr),
				remark:"",						
		};
		processBegin("正在运行中···");
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			if(res.result == 1 && res.data != undefined && res.data != ""){
				processEnd("数据授权成功");
			}else{
				processError("数据授权失败");
			}
		},null,null);
	}
	
	function initDataNodes(rolecode){
		$(".loading",parent.parent.document).show();
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
		var data = {
				cmd:"getGradeAndClass",
				model:"tclass",
				userKey:userKey,
				data:{
					schoolcode:schoolcode
				},
				remark:"",						
		};
		AjaxCrud.get2(serverUrl.ServerLoginUrl,data,function(res){
			var dataNodes = [];
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var root1 = {
						id: "selectAllData",
						pId: -1,
						name : "全部",
						open: true,
				};
				dataNodes.push(root1);
				var data = res.data; 
				for(var i = 0; i < data.length; i++){
					var name = "";
					if(data[i].type == "0"){
						name = "幼儿园";
					}else if(data[i].type == "1"){
						name = "小学";
					}else if(data[i].type == "2"){
						name = "中学";
					}else if(data[i].type == "3"){
						name = "高中";
					}
					var root2 = {
							id: data[i].type + "type",
							pId: "selectAllData",
							name : name,
							open: true,
							type: data[i].type,
					};
					dataNodes.push(root2);
					var gradeData = data[i].typeList;
					for(var j = 0; j < gradeData.length; j++){
						var root3 = {
								id: data[i].type + gradeData[j].grade + "grade",
								pId: data[i].type + "type",
								name : gradeData[j].grade + "年级",
								open: true,
						};
						dataNodes.push(root3);
						var classArr = gradeData[j].classes.split(",");
						var classcodeArr = gradeData[j].classcodes.split(",");
						for(var k = 0; k < classArr.length; k++){
							var root4 = {
									id: classcodeArr[k],
									pId: data[i].type + gradeData[j].grade + "grade",
									name: classArr[k] + "班",
									open: true,
									classes: classArr[k],
									grade: gradeData[j].grade,
									type: data[i].type,
							};
							dataNodes.push(root4);
						}
					}
				}
				$.fn.zTree.init($("#datapower-tree",parent.parent.document), setting, dataNodes);
				getselectedData(rolecode);
			}else{
				var cont = "<span style='margin-left:82px;'>没有查到相关结果！</span>";
				$("#datapower-tree",parent.parent.document).empty().append(cont);
			}
			$(".loading",parent.parent.document).hide();
		},null,null);
	}
	
	function getselectedModels(rolecode){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var data = {
				cmd:"queryUserlicenseModel",
				model:"license",
				userKey:userKey,
				data:{
					code: rolecode,
				},
				remark:"",
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			$(".loading",parent.parent.document).hide();
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var treeObj = $.fn.zTree.getZTreeObj("modelpower-tree");
				var nodes = treeObj.getNodes();
				var data = res.data;
				if(data.length > 0){
					for(var i = 0; i < data.length; i++){
						var children = data[i].children;
						if(children != undefined){
							for(var j = 0; j < children.length; j++){
								var children1 = children[j].children;
								if(children1 != undefined){
									for(var k = 0; k < children1.length; k++){
										if (nodes.length>0) {
											var node = treeObj.getNodeByParam("id",children1[k].code,null);
											treeObj.checkNode(node, true, true);
										}
									}
								}else{
									if (nodes.length>0) {
										var node = treeObj.getNodeByParam("id",children[j].code,null);
										treeObj.checkNode(node, true, true);
									}
								}
							}
						}else{
							if (nodes.length>0) {
								var node = treeObj.getNodeByParam("id",data[i].code,null);
								treeObj.checkNode(node, true, true);
							}
						}
					}
				}
			}
		});
	}
	function getselectedData(rolecode){
		var userKey = $("#user-name",parent.parent.document).attr("key");
		var data = {
				cmd:"getZtreeDataRole",
				model:"license",
				userKey:userKey,
				data:{
					rolecode:rolecode
				},
				remark:"",
		};
		AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
			$(".loading",parent.parent.document).hide();
			if(res.result == 1 && res.data != undefined && res.data != ""){
				var treeObj = $.fn.zTree.getZTreeObj("datapower-tree");
				var nodes = treeObj.getNodes();
				var data = res.data;
				if(data.length > 0){
					for(var i = 0; i < data.length; i++){
						if (nodes.length>0) {
							var node = treeObj.getNodeByParam("id",data[i].classcode,null);
							treeObj.checkNode(node, true, true);
						}
					}
				}
			}
		});
	}
	
	function substr(str,len){
		if(str != undefined){
			if(str.length > len){
				str = str.substring(0,len-2)+"...";
				return str;
			}else{
				return str;
			}
		}else{
			return "";
		}
	}
	function isUndefined(param){
		if(param == undefined){
			param = "";
		}
		return param;
	}
	function getIconUrl(url){
		var urlArr = url.split("../../../");
		return urlArr[1];
	}
	function pagebtns(){
		$("#role-name").unbind("keyup");
		$("#role-name").keyup(function(){
			this.value=this.value.replace(/^ +| +$/g,'');
		});
		document.onkeydown = function(e){ 
		    var ev = document.all ? window.event : e;
		    if(ev.keyCode==13) {
		    	initRole(1,pageSize);
		    }
		};
		$("#role-search-btn").click(function(){
			initRole(1,pageSize);
		});
	}

	function initSmPages(){
		var rcH = $(".body-right",parent.document).height() - $(".right-title").height()-3;
		$(".right-content").height(rcH);
		
		var cdsH = $(".right-content").height() - $(".content-title").height() - 40;
		$(".content-data-show").height(cdsH);
	}
})();